<script lang="ts" setup>
import { ref, reactive, watch, watchEffect } from 'vue'

import { objectToQueryParams } from '@/utils/objectToQuery'
import { formatTableCol, getColWidth, setColWidth, setLastWidth } from './FormatData'
import { isDate, formatDate } from '@/utils/formatDate'
import * as BasicApi from '@/api/index'

import Pagination from './Pagination.vue'
import { useMessage } from '@/hooks/useMessage'
const message = useMessage()

// import DetailModal from './DetailModal.vue'
// import BreakdownModal from './BreakdownModal.vue'
// import { checkTagExists } from '@/utils/checkTagExists'

// const props = defineProps(['partParams', 'compName'])
const props = defineProps({
  partParams: {
    type: Object
  },
  compName: {
    type: String
  }
})

const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数

const list = ref<any[]>([]) // 列表的数据
const column = ref<any[]>([]) // 列表的表头
const listColumn = ref<any[]>([]) //当fieldInfo无 直接取listInfo

const headList = ref<any[]>([]) // 列表的数据
const headColumn = ref<any[]>([]) // 列表的表头

const selectShow = ref() //列表行多选框
const isShowOper = ref() //列表是否有操作
const operList = ref<any[]>([])

const queryParams = reactive({
  type: '',
  value: '',
  keyType: '',
  list: [],
  groupName: '',
  jobType: '',
  pageNo: 1,
  pageSize: 10
})

watch(
  () => props.partParams,
  (val: any) => {
    Object.assign(queryParams, val)
    queryParams.groupName && getList()
  }
)

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true
  try {
    const post = {
      ...queryParams
    }
    const inputStr = objectToQueryParams(post)
    //将Value值放到jsonData中 到时根据keyType是否为多选框再处理Value值
    // keyType为select 直接给数组赋值，若为multiSelect 则取list值
    const jsonData = queryParams.value ? ( queryParams.keyType == 'Select' ? [{ value: queryParams.value}] : queryParams.list) : ''
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any
    const { code, msg, data, rsCount } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    total.value = rsCount
    if (rsCount == 0) {
      list.value = []
      column.value = []
      operList.value = []
      return
    }
    //格式化数据
    const { listInfo, col, listCol, headListInfo, headCol } = formatTableCol(data)
    list.value = listInfo || []
    column.value = col || []
    listColumn.value = listCol || []
    headList.value = headListInfo
    headColumn.value = headCol
    //格式化操作按钮
    const selectArr = data.operInfo && data.operInfo.filter((item: any) => item.Value == 'Select')
    selectShow.value = selectArr && selectArr.length && selectArr[0].IsShow == 'true' ? true : false
    //如果有一项IsShow为true则展示operList
    isShowOper.value =
      data.operInfo &&
      data.operInfo.some((item: any) => item.Value !== 'Select' && item.IsShow == 'true')
    if (isShowOper.value) {
      operList.value =
        data.operInfo &&
        data.operInfo.filter((item: any) => item.Value !== 'Select' && item.IsShow == 'true')
    } else {
      operList.value = []
    }
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['selection-change'])
/** 多选操作 */
const handleSelectionChange = (val: any) => {
  val.length && emit('selection-change', val, headList.value)
}

const modalRef = ref()
/** 编辑弹框 */
const handleEdit = (data: any) => {
  modalRef.value.open(queryParams, data)
}

import eventBus from '@/libs/eventBus'
/** 详情 */
const handleDetail = (data: any) => {
  //打开父组件的详情Tab
  eventBus.emit('addDetailTab', data)
  // localStorage.setItem('WMS_ROW_DATA', JSON.stringify(data))
  // //先判断tag是否存在 存在的话先关闭tag再打开,不存在就正常路由跳转
  // const name = props.compName as any
  // // checkTagExists(name)
  // const post = {
  //   fID: data.FID,
  //   fBillNo: data.FBillNo || '',
  //   type: queryParams.type || ''
  // }
  // const key = name + '_DATA'
  // sessionStorage.setItem(key, JSON.stringify(post))
  // push({
  //   name: props.compName
  // })
}
/** 明细弹框 */
const detailRef = ref()
const breakdownRef = ref()
const handleBreakdown = (data: any) => {
  const { groupName, jobType } = queryParams
  if (groupName == 'BDMgt' && jobType == 'UTR') {
    breakdownRef.value.open(queryParams, data)
  } else {
    detailRef.value.open(queryParams, data)
  }
}

/** 删除按钮操作 */
const handleDelete = async (data: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const inputStr = objectToQueryParams({
      groupName: queryParams.groupName,
      jobType: queryParams.jobType,
      operType: 'Delete'
    })
    const jsonData = data
    const result = (await BasicApi.WMSOper({ inputStr, jsonData })) as any
    const { code, msg } = result
    if (code !== 200) {
      message.error(msg)
      return
    }
    message.success(msg)
    // 刷新列表
    await getList()
  } catch {}
}

const boxRef = ref()
watchEffect(() => {
  let boxWidth = boxRef.value?.offsetWidth
  if (headColumn.value.length) {
    headColumn.value = getColWidth(headColumn.value, boxWidth)
    setLastWidth(headColumn.value, boxWidth)
  }
  if (column.value.length) {
    let resultWidth
    //含有selection则宽度 - 50
    if (selectShow.value) {
      resultWidth = boxWidth - 50
    }
    if (isShowOper.value) {
      resultWidth = boxWidth - 120
    }
    column.value = getColWidth(column.value, resultWidth)
    setLastWidth(column.value, resultWidth)
  }
  if (listColumn.value.length) {
    let resultWidth
    //含有selection则宽度 - 50
    if (selectShow.value) {
      resultWidth = boxWidth - 50
    }
    if (isShowOper.value) {
      resultWidth = boxWidth - 120
    }
    listColumn.value = setColWidth(listColumn.value, resultWidth)
  }
})

// 设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠
// 移动端页码按钮的数量端默认值 5
const width = document.body.clientWidth
const pagerCount = ref(width < 992 ? 5 : 7)
</script>
<template>
  <div ref="boxRef">
    <template v-if="headColumn.length">
      <el-table :data="headList" border stripe style="width: 100%" class="mb-5">
        <template v-for="item in headColumn" :key="item.key">
          <el-table-column
            v-if="item.isShow == 'true'"
            align="center"
            :label="item.label"
            :width="item.width"
            show-overflow-tooltip
          >
            <template #default="scope">
              <template v-if="isDate(item.key)">
                <span>{{ formatDate(scope.row[item.key]) }}</span>
              </template>
              <template v-else>
                <span>{{ scope.row[item.key] }}</span>
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </template>
    <el-table
      v-loading="loading"
      :data="list"
      border
      stripe
      style="width: 100%"
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="selectShow" align="center" type="selection" width="50" />
      <!-- fieldInfo不为空 -->
      <template v-if="column.length">
        <template v-for="item in column" :key="item.value">
          <el-table-column
            v-if="item.isShow == 'true'"
            align="center"
            :label="item.label"
            :width="item.width"
            show-overflow-tooltip
          >
            <template #default="scope">
              <template v-if="isDate(item.value)">
                <span>{{ formatDate(scope.row[item.value]) }}</span>
              </template>
              <template v-else>
                <span>{{ scope.row[item.value] }}</span>
              </template>
            </template>
          </el-table-column>
        </template>
      </template>
      <!-- fieldInfo为空时，直接取ListInfo展示 -->
      <template v-else>
        <el-table-column
          v-for="(column, index) in listColumn"
          :key="index"
          align="center"
          :prop="column.key"
          :label="column.key"
          :width="column.width"
          show-overflow-tooltip
        >
          <template #default="scope">
            <template v-if="isDate(column.key)">
              <span>{{ formatDate(scope.row[column.key]) }}</span>
            </template>
            <template v-else>
              <span>{{ scope.row[column.key] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column v-if="operList.length" fixed="right" label="操作" align="center" width="120">
        <template #default="scope">
          <template v-for="(item, index) in operList" :key="index">
            <template v-if="item.IsShow == 'true'">
              <el-button v-if="item.Value == 'Edit'" link type="primary" @click="handleEdit(item)">
                {{ item.Label }}
              </el-button>
              <el-button
                v-if="item.Value == 'Detail'"
                link
                type="warning"
                @click="handleDetail(list[scope.$index])"
              >
                {{ item.Label }}
              </el-button>
              <el-button
                v-if="item.Value == 'Delete'"
                link
                type="danger"
                @click="handleDelete(list[scope.$index])"
              >
                {{ item.Label }}
              </el-button>
              <el-button
                v-if="item.Value == 'Breakdown'"
                link
                type="success"
                @click="handleBreakdown(list[scope.$index])"
              >
                {{ item.Label }}
              </el-button>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <Pagination
    class="mt-4"
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
  <!-- 表单弹窗：只读详情 -->
  <!-- <DetailModal ref="detailRef" /> -->
  <!-- 可编辑的详情 -->
  <!-- <BreakdownModal ref="breakdownRef" /> -->
</template>
